package com.ncst.backend.service.impl;

import com.ncst.backend.domain.vo.RefundDrugVo;
import com.ncst.backend.domain.vo.RefundPatientVo;
import com.ncst.backend.mapper.RefundMapper;
import com.ncst.backend.service.RefundService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RefundServiceImpl implements RefundService {

    private final RefundMapper refundMapper;

    @Override
    public List<RefundPatientVo> searchPatient(String caseNumber, String realName) {
        return refundMapper.searchPatient(caseNumber, realName);
    }

    @Override
    public List<RefundDrugVo> listRefundableDrugs(String caseNumber, String realName) {
        return refundMapper.listRefundableDrugs(caseNumber, realName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int refund(List<Integer> ids) {
        // 1. 必须是“已发药”
        List<RefundDrugVo> locked = refundMapper.lockItemsByIds(ids);
        if (locked.size() != ids.size()) throw new RuntimeException("存在不可退药品");
        // 2. 改状态
        return refundMapper.updateStateToRefunded(ids);
    }
}